/**
 * 
 */
package feedme.dao.impl;

import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.swing.plaf.basic.BasicArrowButton;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bson.NewBSONDecoder;
import org.bson.types.ObjectId;



import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;

/**
 * DB的连接，一个数据库一个连接，如果用到多个数据库则需要多个实例
 * @author kinzhang
 *
 */
public class MongoDBDriver {
    
    static private Log log = LogFactory.getLog(MongoDBDriver.class);
    /**
     * 配置文件给出host 与 port 
     */
    private String dbHost ;
    private int    dbPort ;
    
    /*
     * 生存的mongo
     */
    private Map<String, DB> dbMap = new HashMap<String, DB>();
    
    /*
     * 生存的mongo
     */
    private Mongo  mongo;
    
    /**
     * 
     */
    public void destory() {
        if (mongo != null)
            mongo.close();
        mongo = null;
        dbMap = null;
    //    db = null;
    //    users = null;
    }
    
    
    DB getDB(String dbName) throws UnknownHostException{
        DB dbValue = this.dbMap.get(dbName);
        if(dbValue == null){
            dbValue = getMongo().getDB(dbName);
            this.dbMap.put(dbName, dbValue);
        }
        return dbValue;
    }
    
    /**
     * @return the dbHost
     */
    public String getDbHost() {
        return dbHost;
    }
    /**
     * @param dbHost the dbHost to set
     */
    public void setDbHost(String dbHost) {
        this.dbHost = dbHost;
    }
    /**
     * @return the dbPort
     */
    public int getDbPort() {
        return dbPort;
    }
    /**
     * @param dbPort the dbPort to set
     */
    public void setDbPort(int dbPort) {
        this.dbPort = dbPort;
    }
    /**
     * @return the mongo
     * @throws UnknownHostException 
     */
    public Mongo getMongo() throws UnknownHostException {
        if (mongo == null) { 
            log.info("init mongo with " + dbHost + ":" + dbPort);
            mongo = new Mongo(dbHost,dbPort);
            log.info("init mongo finished ");
        }
        return mongo;
    }
    /**
     * @param mongo the mongo to set
     */
    public void setMongo(Mongo mongo) {
        this.mongo = mongo;
    }
    

    

    public Map<String, DB> getDbMap() {
        return dbMap;
    }

    public void setDbMap(Map<String, DB> dbMap) {
        this.dbMap = dbMap;
    }

    public static void main(String[] args) throws UnknownHostException, MongoException {
       
   //     SuperString ss = new SuperString();
        
        Mongo mg = new Mongo("172.16.4.19",27017);
        //查询所有的Database
        for (String name : mg.getDatabaseNames()) {
            System.out.println("dbName: " + name);
        }
        
        DB db = mg.getDB("feedme");
        //查询所有的聚集集合
        for (String name : db.getCollectionNames()) {
            System.out.println("collectionName: " + name);
        }
        
        DBCollection users = db.getCollection("order");
        
        BasicDBObject createTime = new BasicDBObject();
        createTime.put("ts", new Date());
        users.insert(createTime, new BasicDBObject("name", "tom")).getN();
        
        //查询所有的数据
        DBCursor cur = users.find();
        while (cur.hasNext()) {
            DBObject object = cur.next();
            System.out.println(object);
            System.out.println(object.get("_id").toString());
        }
        System.out.println(cur.count());
        System.out.println(cur.getCursorId());
        System.out.println(JSON.serialize(cur));
        
        //在 feedme 数据库下增加一条foodServer记录
        
        //先查询所有数据

        
        DBObject user = new BasicDBObject();
        user.put("name", "hoojo");
        user.put("age", 24);
        //users.save(user)保存，getN()获取影响行数
        //print(users.save(user).getN());
        
        //扩展字段，随意添加字段，不影响现有数据
        user.put("sex", "男");
        users.save(user).getN();
        
        //添加多条数据，传递Array对象
        users.insert(user, new BasicDBObject("name", "tom")).getN();
        
        ObjectId oId = new ObjectId("505192352da668c4fc0060fb");
        System.out.println(oId.toString());
        System.out.println(oId.toStringBabble());
        System.out.println(oId.toStringMongod());
        System.out.println("ObjectId(" +"\"" + oId + "\")");
        
        System.out.println( 
            users.remove(
                    new BasicDBObject("_id", new ObjectId("5051b2a1f7eed0335cbfc8be"))
                ).getN() 
            );
    }
    
}
